<template>
  <a
      v-if="showAd"
      class="floating-ad"
      :href="currentAd.link"
      target="_blank"
      @mouseover="pauseAd"
      @mouseleave="resumeAd"
      :style="{ top: adPosition.top + 'px', left: adPosition.left + 'px' }"
  >
    <img :src="currentAd.image" alt="广告" class="ad-image" />
    <span class="ad-close" @click.prevent="closeAd">✖</span>
  </a>
</template>

<script>
export default {
  name: "FlyingAd",
  data() {
    return {
      showAd: true,
      adPosition: { top: 100, left: 100 },
      adInterval: null,
      adList: [
        { image: '/ads/ad1.jpg', link: 'https://example.com/ad1' },
        { image: '/ads/ad2.jpg', link: 'https://example.com/ad2' },
        { image: '/ads/ad3.jpg', link: 'https://example.com/ad3' }
      ],
      currentAdIndex: 0,
      adSwitchInterval: null
    };
  },
  computed: {
    currentAd() {
      return this.adList[this.currentAdIndex];
    }
  },
  methods: {
    moveAd() {
      const maxTop = window.innerHeight - 120;
      const maxLeft = window.innerWidth - 220;
      this.adPosition.top = Math.floor(Math.random() * maxTop);
      this.adPosition.left = Math.floor(Math.random() * maxLeft);
    },
    pauseAd() {
      clearInterval(this.adInterval);
    },
    resumeAd() {
      this.adInterval = setInterval(this.moveAd, 1500);
    },
    closeAd() {
      this.showAd = false;
      clearInterval(this.adInterval);
      clearInterval(this.adSwitchInterval);
    },
    switchAd() {
      this.currentAdIndex = (this.currentAdIndex + 1) % this.adList.length;
    }
  },
  mounted() {
    this.adInterval = setInterval(this.moveAd, 1500);
    this.adSwitchInterval = setInterval(this.switchAd, 4000);
  },
  beforeUnmount() {
    clearInterval(this.adInterval);
    clearInterval(this.adSwitchInterval);
  }
};
</script>

<style scoped>
.floating-ad {
  position: fixed;
  z-index: 9999;
  background: #fff;
  padding: 2px;
  border-radius: 6px;
  box-shadow: 0 0 10px rgba(0,0,0,0.3);
  transition: top 0.5s ease, left 0.5s ease;
  display: inline-block;
}
.ad-image {
  width: 200px;
  height: 100px;
  display: block;
  border-radius: 4px;
}
.ad-close {
  position: absolute;
  top: -8px;
  right: -8px;
  background: red;
  color: white;
  font-size: 12px;
  width: 16px;
  height: 16px;
  border-radius: 50%;
  text-align: center;
  line-height: 16px;
  cursor: pointer;
}
</style>